package com.TropicalFlavor.controller;

import com.TropicalFlavor.po.*;
import com.TropicalFlavor.service.AdminService;
import com.TropicalFlavor.service.GoodsService;
import com.TropicalFlavor.service.UserService;
import com.TropicalFlavor.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@Slf4j
public class userController
{
    @Resource
    private UserService service;

    @Resource
    private GoodsService goodsService;

    @Resource
    private AdminService adminService;

    //登出
    @RequestMapping(value = "/logout.do")
    public String logout(HttpServletRequest request) {
        try {
            request.getSession().removeAttribute("marketUser");
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/home.do";
        }
        return "redirect:/";
    }

    //进入登录页面
    @RequestMapping(value = "/login.do", method = RequestMethod.GET)
    public String login(HttpServletRequest request, Model model) {
        return "page/login_page";
    }

    //登录
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public String login(HttpServletRequest request, @RequestParam String sNum,
                        @RequestParam String Password, @RequestParam boolean isAdmin,
                        Model model) {
        String loginMessage = "";
        if (StringUtils.getInstance().isNullOrEmpty(sNum) || StringUtils.getInstance().isNullOrEmpty(Password))
        {
            loginMessage = "用户名或密码不能为空！";
            model.addAttribute("loginMessage", loginMessage);
            return "page/login_page";
        }
        MarketUser user = service.Login(sNum, Password, isAdmin);
        if (user == null) {
            loginMessage = "用户名或密码错误！";
            model.addAttribute("loginMessage", loginMessage);
            return "page/login_page";
        }
        String access;
        if(isAdmin)
        {
            access = "Admin";
        }
        else
        {
            access = "Norm";
        }
        request.getSession().setAttribute("access", access);
        request.getSession().setAttribute("marketUser", user);
        return "redirect:/";
    }

    //查看用户基本信息
    @RequestMapping(value = "/personal_info.do")
    public String personInfo(HttpServletRequest request, Model model) {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        String access = (String) request.getSession().getAttribute("access");
        if (StringUtils.getInstance().isNullOrEmpty(user))
            return "page/login_page";
        model.addAttribute("access", access);
        model.addAttribute("marketUser", user);
        return "page/personal/information";
    }

    @RequestMapping(value = "/goToEditPersonalInfo.do")
    public String goToEditPersonInfo(HttpServletRequest request, Model model) {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        model.addAttribute("marketUser", user);
        return "page/editperson";
    }

    //修改用户信息
    @RequestMapping(value = "/editPersonalInfo.do", method = RequestMethod.POST)
    //@ResponseBody
    public String editPersonalInfo(HttpServletRequest request, Model model,
                                   @RequestParam(required = false) String Uname,
                                   @RequestParam(required = false) String Password,
                                   @RequestParam(required = false) String PhoneNum,
                                   @RequestParam(required = false) String Email
    ) {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");

        //model.addAttribute("marketUser", user);

        //符合要求即可修改，否则重新加载页面
        if (!Uname.isEmpty()) {
            if (Uname.length() <= 30)
                user.setUname(Uname);
            else
            {

                return "redirect:/goToEditPersonalInfo.do";
            }
        }

        if (!Password.isEmpty()) {
            if (Password.length() <= 16)
                user.setPassword(Password);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

        if (!PhoneNum.isEmpty()) {
            if (PhoneNum.length() <= 11)
                user.setPhoneNum(PhoneNum);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

        if (!Email.isEmpty()) {
            if (Email.length() <= 50)
                user.setEmail(Email);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

        boolean isEditSuccess = service.ChangeInfo(user);
        if (!isEditSuccess)
            return "redirect:/goToEditPersonalInfo.do";

        request.getSession().setAttribute("marketUser", user);
        return "redirect:/personal_info.do";
    }

//    public String getGID()
//    {
//        return String.format("%d",utilsDao.selectMaxGID()+1);
//    }
//    public String getPID()
//    {
//        return String.format("%d",utilsDao.selectMaxPID()+1);
//    }

    //用户上传商品
    @RequestMapping(value = "/insertGoods.do", method = RequestMethod.POST)
    public String insertGoods(@RequestParam(required = false) MultipartFile image,
                              @RequestParam String Name,
                              @RequestParam String Kind,
                              @RequestParam Double Price,
                              @RequestParam Double Number,
                              HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        model.addAttribute("marketUser", user);

//        if(GID.isEmpty() || Name.isEmpty() || Kind == null || Price == null || Number == null)
//        {
//            return "redirect:/publish_product.do";
//        }

        //System.out.println(action);

        //新增商品
        if (StringUtils.getInstance().isNullOrEmpty(Name) ||
                StringUtils.getInstance().isNullOrEmpty(Kind) ||
                StringUtils.getInstance().isNullOrEmpty(Price) ||
                StringUtils.getInstance().isNullOrEmpty(Number))
            return "redirect:/publish_product.do";

        MarketGoods goods = new MarketGoods(Name, Kind, Price, Number);

        boolean isInsertGoodsSuccess = service.PushSaleGoods(user.getUID(), goods);

        if (isInsertGoodsSuccess) {
            model.addAttribute("marketGoods", goods);
            model.addAttribute("marketUser", user);
            model.addAttribute("action", 2);
            return "redirect:/personal_info.do";
        } else
            return "redirect:/publish_product.do";
    }

    //进入我的商品页面
    @RequestMapping(value = "/my_publish_product_page.do")
    public String showMyProduct(HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        model.addAttribute("marketUser", user);

        SaleGoods goods = service.ShowSales(user);

        model.addAttribute("marketGoodsList", goods.getGoods());

        return "page/personal/my_publish_product";
    }

    //下架商品
    @RequestMapping(value = "/deleteGoods.do")
    public String deleteMyProduct(HttpServletRequest request, Model model, @RequestParam String GID)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        model.addAttribute("marketUser", user);

        MarketGoods marketGoods = goodsService.SelectGoodsByPK(GID);

        service.RemoveSaleGoods(user.getUID(), marketGoods);

        return "redirect:/my_publish_product_page.do";
    }

    //进入修改商品信息页面
    @RequestMapping(value = "/modifiedPublishProduct.do")
    public String modifyMyProduct(HttpServletRequest request, Model model, @RequestParam String GID)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");

        MarketGoods goods = goodsService.SelectGoodsByPK(GID);

        //System.out.println(goods);

        model.addAttribute("marketUser", user);
        model.addAttribute("marketGoods", goods);

        request.getSession().setAttribute("marketGoods", goods);

        return "page/edit_product_info";
    }

    //修改商品信息
    @RequestMapping(value = "/modifyProductInfo.do", method = RequestMethod.POST)
    public String modifyProduct(@RequestParam(required = false) MultipartFile img,
                                @RequestParam(required = false) String Name,
                                @RequestParam(required = false) String Kind,
                                @RequestParam(required = false) Double Price,
                                @RequestParam(required = false) Double Number,
                                HttpServletRequest request, Model model)
    {
        MarketGoods goods = (MarketGoods) request.getSession().getAttribute("marketGoods");
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");

        //System.out.println(goods);

        goods.setName(Name);
        goods.setKind(Kind);
        goods.setPrice(Price);
        goods.setNumber(Number);

        boolean isEditSuccess = goodsService.ChangeGoodsInfo(goods);

        if(!isEditSuccess)
            return "redirect:/modifiedPublishProduct.do";
        else
        {
            model.addAttribute("marketGoods", goods);
            return "redirect:/my_publish_product_page.do";

        }
    }

    //用户点击立即购买商品
    @RequestMapping(value = "/buyDirectly.do", method = RequestMethod.POST)
    //@ResponseBody
    public String buyDirectly(HttpServletRequest request, Model model, @RequestParam String GID, @RequestParam Double Number) {
        MarketGoods goods = goodsService.SelectGoodsByPK(GID);
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String[] time = formatter.format(date).split(" ");
        String Day = time[0];
        String Time = time[1];

        Integer buyStatus = service.BuyDirectly(user.getUID(), goods, Time, Day, Number);

        if (buyStatus == 2)
        {
            model.addAttribute("marketUser", user);
            return "redirect:/goToMallPage.do";
        }
        else if (buyStatus == 1)
        {
            model.addAttribute("marketUser", user);
            String message = "购买失败，不能购买自己的商品";
            model.addAttribute("message", message);
            model.addAttribute("marketGoods", goods);
            return "page/buy";
        }
        else
        {
            model.addAttribute("marketUser", user);
            String message = "超出最大购买数量";
            model.addAttribute("message", message);
            model.addAttribute("marketGoods", goods);
            return "page/buy";
        }

    }

    //用户点击我的购买记录
    @RequestMapping(value = "/my_buy_history.do")
    public String goToMyHistory(HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        PurchaseRecordList purchaseRecordList = service.ShowPRecord(user);

        List<PurchaseRecord> myList = purchaseRecordList.getPurchaseRecordList();

        System.out.println(myList);

        request.getSession().setAttribute("myRecordList", myList);

        model.addAttribute("marketUser", user);
        model.addAttribute("myRecordList", myList);
        return "/page/personal/my_buy_history";
    }

    //我的购物车
    @RequestMapping(value = "/goToMyCart.do")
    public String goToMyCart(HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        if(StringUtils.getInstance().isNullOrEmpty(user))
        {
            return "page/login_page";
        }


        model.addAttribute("marketUser", user);

        return "page/cart";

    }

}
